package com.sunyard.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.page.PageMethod;
import com.sunyard.dal.bo.device.car.CarAuditBO;
import com.sunyard.dal.bo.device.car.CarDeleteBO;
import com.sunyard.dal.bo.PaginationBO;
import com.sunyard.dal.dto.CarCopyDTO;
import com.sunyard.dal.dto.CarCopyResltDTO;
import com.sunyard.dal.dto.CarDTO;
import com.sunyard.dal.dto.CarReslutDTO;
import com.sunyard.dal.entity.Car;
import com.sunyard.dal.entity.CarCopy;
import com.sunyard.dal.entity.Operator;
import com.sunyard.dal.entity.Organization;
import com.sunyard.dal.mapper.CarCopyMapper;
import com.sunyard.dal.mapper.CarMapper;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.OrganizationMapper;
import com.sunyard.enums.AuditTypeEnum;
import com.sunyard.enums.IsCheckEnum;
import com.sunyard.enums.IsDeletedEnum;
import com.sunyard.manage.service.CarService;
import com.sunyard.manage.service.OperatorLogService;
import com.sunyard.manage.service.OrganizationService;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.ExcelOutput;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import com.sunyard.utils.manage.DataGrid;
import com.sunyard.utils.manage.PageQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * @author: ZhangShuai
 * @description:
 * @create: 2022-07-07 17:50
 **/
@Slf4j
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private OperatorMapper operatorMapper;

    @Autowired
    private CarMapper carMapper;

    @Autowired
    private CarCopyMapper carCopyMapper;

    @Autowired
    private OperatorLogService operatorLogService;

    @Autowired
    private OrganizationService organizationService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult delete(CarDTO car, HttpServletRequest request) {
        log.info("删除车俩信息的入参为{}", JSON.toJSONString(car));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("用户无权限！");
        }
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        String isCheck = car.getIsCheck();
        car.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        Car chechCar = carMapper.selectById(car.getId());
        if (IsDeletedEnum.DELETED.getCode().equals(chechCar.getIsDeleted())) {
            return GetResult.getResultFail("数据已删除！");
        }
        CarCopyDTO copy = carCopyMapper.selectByCarId(car.getId());
        if (ObjectUtil.isNotNull(copy)) {
            return GetResult.getResultFail("该车辆存在未审核数据，无法删除");
        }
        //同步
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(isCheck)) {
            carMapper.updateByPrimaryKeySelective(car);

            // carCopyMapper.deleteByCarId(String.valueOf(car.getId()));
        }
        copy = new CarCopyDTO();
        BeanUtil.copyProperties(chechCar, copy);
        Car carInfo = carMapper.selectById(car.getId());
        Integer id = null;
        if (ObjectUtil.isNull(copy)) {
            copy = new CarCopyDTO();
            BeanUtil.copyProperties(carInfo, copy);
        } else {
            id = copy.getId();
            BeanUtil.copyProperties(chechCar, copy);
        }
        copy.setId(id);
        copy.setCarId(car.getId());
        copy.setOperateType(AuditTypeEnum.DELETE.getCode());
        copy.setAdminId(opId);
        //同步复核人是操作员，异步是指派人
        copy.setCheckAdminId(car.getAdminId());
        copy.setUseAdminId(opId);
        copy.setIsCheck(car.getIsCheck());
        // if (copy.getId() != null) {
        //     copy.setId(id);
        //     copy.setIsDeleted(IsDeletedEnum.DELETED.getCode());
        //     carCopyMapper.updateByPrimaryKeySelective(copy);
        // } else {
        //     copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        //     carCopyMapper.insertQuery(copy);
        // }
        copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        carCopyMapper.insertQuery(copy);
        operatorLogService.insert("删除车辆信息", "删除车辆", "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("删除成功");
    }

    @Override
    public BaseResult batchDeleteCar(CarDeleteBO deleteBO, HttpServletRequest request) {
        String[] ids = deleteBO.getId().split(",");
        for (String id : ids) {
            CarDTO carDTO = new CarDTO();
//            BeanUtil.copyProperties(deleteBO, carDTO);
            carDTO.setId(Integer.valueOf(id));
            carDTO.setIsCheck(deleteBO.getAuditType());
            carDTO.setAdminId(deleteBO.getAuditor());
            BaseResult result = delete(carDTO, request);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        String message = "1".equals(deleteBO.getAuditType()) ? "删除车辆成功！" : "删除车辆成功，待审核！";
        return GetResult.getResultSuccess(message);
    }

    @Override
    public BaseResult exportCar(PaginationBO<CarDTO> queryBO, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CarDTO params = queryBO.getParams();
        log.info("导出车俩信息的入参为{}", JSON.toJSONString(params));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isBlank(params.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            params.setOrgId(org);
        } else {
            String org = getOrgIdAllChild(params.getOrgId());
            params.setOrgId(org);
        }
        List<Car> resultCar = carMapper.getPageInfo(params);

        String title = "车辆信息导出";
        String[] headers = new String[]{"车辆名称", "车辆所属机构", "车牌号", "联系人电话", "审核状态", "联系人名称", "公司名称", "指派人"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        dataList = resultCar.stream().map(car -> {
            Object[] obj = new Object[headers.length];
            obj[0] = car.getCarName();
            String orgName = organizationMapper.getOrgName(car.getOrgId());
            obj[1] = orgName;
            obj[2] = car.getCarPlate();
            obj[3] = car.getContactPhone();
            String isCheck = car.getIsCheck();
            //审核状态（0未审核，1通过，2未通过）
            if (IsCheckEnum.PASS_CHECKED.getCode().equals(isCheck)) {
                isCheck = "审核通过";
            } else if (IsCheckEnum.NOT_PASS_CHECKED.getCode().equals(isCheck)) {
                isCheck = "审核未通过";
            } else {
                isCheck = "未审核";
            }
            obj[4] = isCheck;
            obj[5] = car.getContactName();
            obj[6] = car.getCompany();
            String admin = car.getAdminId();
            obj[7] = operatorMapper.getOperatorByOpId(admin).getOpName();
            return obj;
        }).collect(toList());
        OutputStream out = null;
        // 防止中文乱码
        String headStr = "attachment; filename=\"" + new String(title.getBytes("gb2312"), "ISO8859-1") + "\"";
        response.setContentType("octets/stream");
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", headStr);
        out = response.getOutputStream();
        ExcelOutput ex = new ExcelOutput(title, headers, dataList);
        ex.export(out);
        operatorLogService.insert("导出车辆信息", "导出车辆", "1", opId, operator.getOpName(), orgId);
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult addCarInfo(CarDTO car, HttpServletRequest request) throws Exception {
        log.info("批量新增车俩信息的入参为{}", JSON.toJSONString(car));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Car resultCat = carMapper.quetyCarName(car.getCarName(), null);
        if (ObjectUtil.isNotNull(resultCat)) {
            throw new Exception("添加车辆信息的名称重复，请核查后重新输入！");
        }
        Car queryCar = carMapper.queryByCarPlate(car.getCarPlate(), null);
        if (queryCar != null && car.getCarPlate().equals(queryCar.getCarPlate())) {
            throw new Exception("添加车辆信息的车牌号重复，请核查后重新输入！");
        }
        if (queryCar != null && car.getCarName().equals(queryCar.getCarName())) {
            throw new Exception("添加车辆信息的车牌名称重复，请核查后重新输入！");
        }
        car.setCreateTime(new Date());
        Organization organization = organizationMapper.getOrganizationByOrgId(car.getOrgId());
        /**
         * 20220916 tk
         */
        if (organization != null){
            if ("".equals(organization.getOrgType()) || !"4".equals(organization.getOrgType())){
                return GetResult.getResultFail("车辆信息添加失败, 机构类型不符！");
            }
            if ("".equals(organization.getOrgStatus()) || !"0".equals(organization.getOrgStatus())){
                return GetResult.getResultFail("车辆信息添加失败, 机构状态不符！");
            }
            car.setOrgName(organization.getOrgName());
        }
        //机构等级：1-一级机构，2-二级机构，3-三级机构，4-四级机构，5-五级机构
        String orgLevel = String.valueOf(organization.getOrgLevel());
        switch (orgLevel) {
            case "1":
                orgLevel = "一级机构";
                break;
            case "2":
                orgLevel = "二级机构";
                break;
            case "3":
                orgLevel = "三级机构";
                break;
            case "4":
                orgLevel = "四级机构";
                break;
            default:
                orgLevel = "五级机构";
        }
        car.setOrgLevel(orgLevel);
        car.setCompany(organization.getOrgName());
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        car.setCreateUser(operator.getOpName());
        carMapper.insertSelective(car);

        // CarCopy copy = new CarCopy();
        // Car carInfo = carMapper.quetyCarName(car.getCarName());
        // BeanUtil.copyProperties(carInfo, copy);
        // copy.setCheckAdminId(car.getAdminId());
        // if (IsCheckEnum.PASS_CHECKED.getCode().equals(car.getIsCheck())) {
        //     //同步审核
        //     copy.setCheckAdminId(opId);
        // }
        // copy.setId(null);
        // copy.setCarId(carInfo.getId());
        // copy.setOperateType(AuditTypeEnum.ADD.getCode());
        // copy.setAdminId(opId);
        // copy.setUseAdminId(opId);
        // copy.setAuditDetails(car.getIsCheck());
        // copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
        // carCopyMapper.insert(copy);
        operatorLogService.insert("新增车辆信息", "新增车辆", "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("车辆信息添加成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult<Car> updateCar(CarDTO car, HttpServletRequest request) {
        log.info("修改车俩信息的入参为{}", JSON.toJSONString(car));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        Car resultCat = carMapper.quetyCarName(car.getCarName(), String.valueOf(car.getId()));
        if (ObjectUtil.isNotNull(resultCat)) {
            return GetResult.getResultFail("车辆信息的名称重复，请核查后重新输入！");
        }
        Car queryCar = carMapper.queryByCarPlate(car.getCarPlate(), String.valueOf(car.getId()));
        if (queryCar != null && car.getCarPlate().equals(queryCar.getCarPlate())) {
            return GetResult.getResultFail("车辆信息的车牌号重复，请核查后重新输入！");
        }
        CarCopyDTO copy = carCopyMapper.selectByCarId(car.getId());
        if (ObjectUtil.isNotNull(copy)){
            return GetResult.getResultFail("该车辆存在未审核信息，无法修改");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        Organization name = organizationMapper.getOrganizationByOrgId(car.getOrgId());
        car.setCompany(name.getOrgName());
        car.setOrgName(name.getOrgName());
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(car.getIsCheck())) {
            carMapper.updateByPrimaryKeySelective(car);
        }
        Car carInfo = carMapper.selectById(car.getId());
        Integer id = null;
        if (ObjectUtil.isNull(copy)) {
            copy = new CarCopyDTO();
            BeanUtil.copyProperties(carInfo, copy);
            if (!StringUtils.isEmpty(car.getCarName())) {
                copy.setCarName(car.getCarName());
            }
            if (!StringUtils.isEmpty(car.getCarPlate())) {
                copy.setCarPlate(car.getCarPlate());
            }
            if (!StringUtils.isEmpty(car.getOrgId())) {
                copy.setOrgId(car.getOrgId());
                Organization organization = organizationMapper.getOrganizationByOrgId(car.getOrgId());
                copy.setOrgName(organization.getOrgName());
            }
            if (!StringUtils.isEmpty(car.getCompany())) {
                copy.setCompany(car.getCompany());
            }
            if (!StringUtils.isEmpty(car.getContactName())) {
                copy.setContactName(car.getContactName());
            }
            if (!StringUtils.isEmpty(car.getContactPhone())) {
                copy.setContactPhone(car.getContactPhone());
            }
        } else {
            id = copy.getId();
            BeanUtil.copyProperties(car, copy);
        }
        copy.setId(id);
        copy.setCarId(car.getId());
        copy.setOperateType(AuditTypeEnum.UPDATE.getCode());
        copy.setAdminId(opId);
        //同步复核人是操作员，异步是指派人
        copy.setCheckAdminId(car.getAdminId());
        copy.setUseAdminId(opId);
        copy.setIsCheck(car.getIsCheck());
        if (copy.getId() != null) {
            copy.setId(id);
            carCopyMapper.updateByPrimaryKeySelective(copy);
        } else {
            copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
            carCopyMapper.insertQuery(copy);
        }
        operatorLogService.insert("修改车辆信息", "修改车辆", "1", opId, operator.getOpName(), orgId);
        /*if (true){
            throw new RuntimeException();
        }*/
        return GetResult.getResultSuccess("车辆信息修改成功！");

    }

    @Override
    public BaseResult<DataGrid<CarReslutDTO>> getCarByPage(PaginationBO<CarDTO> queryBO, HttpServletRequest request) throws Exception {
        CarDTO params = queryBO.getParams();
        log.info("查询车俩信息的入参为{}", JSON.toJSONString(params));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isBlank(params.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            params.setOrgId(org);
        } else {
            String org = getOrgIdAllChild(params.getOrgId());
            params.setOrgId(org);
        }
        PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        List<Car> carInfoList = carMapper.getPageInfo(params);
        List<CarReslutDTO> reslutDTOS = new ArrayList<>();
        for (Car car : carInfoList) {
            CarReslutDTO dto = new CarReslutDTO();
            BeanUtil.copyProperties(car, dto);
            dto.setCreateTime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, car.getCreateTime()));
            reslutDTOS.add(dto);
        }
        DataGrid dataGrid = PageQuery.getDataGrids(carInfoList, reslutDTOS);
        operatorLogService.insert("查询车辆信息", "查询车辆", "1", opId, operator.getOpName(), orgId);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult auditCarInfo(CarCopyDTO carCopy, HttpServletRequest request) {
        log.info("审核车俩信息的入参为{}", JSON.toJSONString(carCopy));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        CarCopy resultCopy = carCopyMapper.queryNotAuditInfo(carCopy);
        Organization organization = organizationMapper.getOrganizationByOrgId(resultCopy.getOrgId());
        if (ObjectUtil.isNull(organization)) {
            return GetResult.getResultFail("车辆" + resultCopy.getCarName() + "所属机构不存在，无法审核");
        }
        //判断当前登录用户是否是指定审核人
        if (!opId.equals(resultCopy.getCheckAdminId())) {
            return GetResult.getResultFail("当前用户没有审核权限！");
        }
        Car car = new Car();
        CarDTO carDTO = new CarDTO();
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(carCopy.getIsCheck())) {
            if (AuditTypeEnum.ADD.getCode().equals(resultCopy.getOperateType())) {
                BeanUtil.copyProperties(resultCopy, car);
                Car resultCat = carMapper.quetyCarName(resultCopy.getCarName(), null);
                if (ObjectUtil.isNotNull(resultCat)) {
                    return GetResult.getResultFail("车辆信息的名称重复，请核查后重新输入！");
                }
                Car queryCar = carMapper.queryByCarPlate(resultCopy.getCarPlate(), null);
                if (queryCar != null && car.getCarPlate().equals(queryCar.getCarPlate())) {
                    return GetResult.getResultFail("车辆信息的车牌号重复，请核查后重新输入！");
                }
                car.setId(null);
                car.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
                car.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
                carMapper.insert(car);

                Car car1 = carMapper.queryByCarPlate(car.getCarPlate(), null);
                CarCopyDTO copy = new CarCopyDTO();
                copy.setId(resultCopy.getId());
                copy.setCarId(car1.getId());

                carCopyMapper.updateByPrimaryKeySelective(copy);
            } else if (AuditTypeEnum.DELETE.getCode().equals(resultCopy.getOperateType())) {
                carDTO.setId(resultCopy.getCarId());
                carDTO.setIsDeleted(IsDeletedEnum.DELETED.getCode());
                carMapper.updateByPrimaryKeySelective(carDTO);

                carCopyMapper.deleteByCarId(String.valueOf(resultCopy.getCarId()));
            } else {
                //审核 修改
                BeanUtil.copyProperties(resultCopy, carDTO);
                Car resultCat = carMapper.quetyCarName(resultCopy.getCarName(), String.valueOf(resultCopy.getCarId()));
                if (ObjectUtil.isNotNull(resultCat)) {
                    return GetResult.getResultFail("车辆信息的名称重复，请核查后重新输入！");
                }
                Car queryCar = carMapper.queryByCarPlate(resultCopy.getCarPlate(), String.valueOf(resultCopy.getCarId()));
                if (queryCar != null && car.getCarPlate().equals(queryCar.getCarPlate())) {
                    return GetResult.getResultFail("车辆信息的车牌号重复，请核查后重新输入！");
                }
                carDTO.setId(resultCopy.getCarId());
                carDTO.setIsCheck(carCopy.getIsCheck());
                carMapper.updateByPrimaryKeySelective(carDTO);


            }
            CarCopyDTO updateStatus = new CarCopyDTO();
            updateStatus.setIsCheck(IsCheckEnum.PASS_CHECKED.getCode());
            updateStatus.setId(carCopy.getId());
            if (!StringUtils.isEmpty(carCopy.getAuditDetails())) {
                updateStatus.setAuditDetails(carCopy.getAuditDetails());
            }
            carCopyMapper.updateByPrimaryKeySelective(updateStatus);
        } else if (IsCheckEnum.NOT_PASS_CHECKED.getCode().equals(carCopy.getIsCheck())) {
            //若审核不通过 审核状态 0未审核 1复核通过 2审核不通过")
            CarCopyDTO copy = new CarCopyDTO();
            if (!StringUtils.isEmpty(carCopy.getAuditDetails())) {
                copy.setAuditDetails(carCopy.getAuditDetails());
            }
            copy.setIsCheck(carCopy.getIsCheck());
            copy.setId(carCopy.getId());
            carCopyMapper.updateByPrimaryKeySelective(copy);

        }
        operatorLogService.insert("审核车辆信息", "审核车辆", "1", opId, operator.getOpName(), orgId);
        return GetResult.getResultSuccess("审核成功！");
    }

    @Override
    public BaseResult batchAuditCarInfo(CarAuditBO carAuditBO, HttpServletRequest request) {
        String[] ids = carAuditBO.getId().split(",");
        for (String id : ids) {
            CarCopyDTO carCopyDTO = new CarCopyDTO();
            carCopyDTO.setId(Integer.valueOf(id));
            carCopyDTO.setIsCheck(String.valueOf(carAuditBO.getAuditFlag()));
            carCopyDTO.setAuditDetails(carAuditBO.getAuditDesc());
            BaseResult result = auditCarInfo(carCopyDTO, request);
            if (!"00".equals(result.getDataCode())) {
                return GetResult.getResultFail(result.getDataMessage());
            }
        }
        return GetResult.getResultSuccess("审核成功");
    }

    @Override
    public BaseResult<DataGrid<CarCopyResltDTO>> queryCarCopyByPage(PaginationBO<CarCopyDTO> queryBO, HttpServletRequest request) throws Exception {
        CarCopyDTO params = queryBO.getParams();
        log.info("查询车辆审核信息的入参为{}", JSON.toJSONString(params));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isBlank(params.getOrgId())) {
            String org = getOrgIdAllChild(orgId);
            params.setOrgId(org);
        } else {
            String org = getOrgIdAllChild(params.getOrgId());
            params.setOrgId(org);
        }
        PageMethod.startPage(queryBO.getPageNo(), queryBO.getPageSize());
        List<CarCopy> resultList = carCopyMapper.queryCarCopyByPage(params);


        List<CarCopyResltDTO> resltDTOS = new ArrayList<>();
        for (CarCopy copy : resultList) {
            CarCopyResltDTO dto = new CarCopyResltDTO();
            BeanUtil.copyProperties(copy, dto);
            dto.setIsDeleted(copy.getIsDeleted());
            dto.setCreateTime(DateUtil.getDateStr(DateUtil.YYYYMMDD_HHMMSS, copy.getCreateTime()));
            dto.setAdminId(operatorMapper.getOperatorByOpId(dto.getAdminId()).getOpName());
            dto.setCheckAdminId(operatorMapper.getOperatorByOpId(dto.getCheckAdminId()).getOpName());
            resltDTOS.add(dto);
        }
        DataGrid dataGrid = PageQuery.getDataGrids(resultList, resltDTOS);
        operatorLogService.insert("查询审核车辆信息", "查询审核车辆", "1", opId, operator.getOpName(), orgId);
        return GetResult.getResult(dataGrid);
    }

    @Override
    public BaseResult<Map<String, CarCopy>> queryAuditInfo(CarCopyDTO carCopyDTO, HttpServletRequest request) throws Exception {
        log.info("查询车辆审核详情的入参为{}", JSON.toJSONString(carCopyDTO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        Map<String, CarCopy> map = new HashMap<>();
        CarCopy carCopy = carCopyMapper.selectByPrimaryKey(carCopyDTO.getId());
        operatorLogService.insert("查询审核车辆详情", "查询车辆", "1", opId, operator.getOpName(), orgId);
        if (AuditTypeEnum.ADD.getCode().equals(carCopy.getOperateType())) {
            map.put("oldData", null);
            map.put("newDate", carCopy);
            return GetResult.getResult(map);
        } else if (AuditTypeEnum.DELETE.getCode().equals(carCopy.getOperateType())) {
            map.put("oldData", carCopy);
            map.put("newDate", null);
            return GetResult.getResult(map);
        } else {
            Car car = carMapper.selectById(carCopy.getCarId());
            List<CarCopy> list = carCopyMapper.selectByAuditByCarId(String.valueOf(carCopyDTO.getId()), String.valueOf(carCopy.getCarId()));
            if (!list.isEmpty()) {
                map.put("oldData", list.get(0));
                CarCopy copy = new CarCopy();
                BeanUtil.copyProperties(car, copy);
                map.put("newDate", carCopy);
            }
            return GetResult.getResult(map);
        }
    }

    @Override
    public BaseResult<List<Car>> queryCarByOrgId(CarDTO carDTO, HttpServletRequest request) {
        log.info("查询车辆信息入参为{}", JSON.toJSONString(carDTO));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        List<String> stringList = new ArrayList<>();
        stringList.add(carDTO.getOrgId());
        List<Car> list = carMapper.getCarInfoByOrgList(stringList);
        return GetResult.getResult(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult addCar(CarDTO car, HttpServletRequest request) {
        log.info("批量新增车俩信息的入参为{}", JSON.toJSONString(car));
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        if (StringUtils.isEmpty(opId)) {
            return GetResult.getResultFail("请先登陆系统");
        }
        Car resultCat = carMapper.quetyCarName(car.getCarName(), null);
        if (ObjectUtil.isNotNull(resultCat)) {
            return GetResult.getResultFail("添加车辆信息的名称重复，请核查后重新输入！");
        }
        Car queryCar = carMapper.queryByCarPlate(car.getCarPlate(), null);
        if (queryCar != null && car.getCarPlate().equals(queryCar.getCarPlate())) {
            return GetResult.getResultFail("添加车辆信息的车牌号重复，请核查后重新输入！");
        }
        car.setCreateTime(new Date());
        Organization organization = organizationMapper.getOrganizationByOrgId(car.getOrgId());
        car.setOrgName(organization.getOrgName());
        //机构等级：1-一级机构，2-二级机构，3-三级机构，4-四级机构，5-五级机构
        String orgLevel = String.valueOf(organization.getOrgLevel());
        switch (orgLevel) {
            case "1":
                orgLevel = "一级机构";
                break;
            case "2":
                orgLevel = "二级机构";
                break;
            case "3":
                orgLevel = "三级机构";
                break;
            case "4":
                orgLevel = "四级机构";
                break;
            default:
                orgLevel = "五级机构";
        }
        car.setCompany(organization.getOrgName());
        car.setOrgLevel(orgLevel);
        Operator operator = operatorMapper.getOperatorByOpId(opId);
        car.setCreateUser(operator.getOpName());
        String msg = "";
        if (IsCheckEnum.PASS_CHECKED.getCode().equals(car.getIsCheck())) {
            carMapper.insertSelective(car);

            CarCopy copy = new CarCopy();
            Car carInfo = carMapper.queryByCarPlate(car.getCarPlate(), null);
            BeanUtil.copyProperties(carInfo, copy);
            copy.setCheckAdminId(car.getAdminId());
            copy.setId(null);
            copy.setCarId(carInfo.getId());
            copy.setOperateType(AuditTypeEnum.ADD.getCode());
            copy.setUseAdminId(opId);
            copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
            carCopyMapper.insert(copy);
        } else {
            CarCopy copy = new CarCopy();
            BeanUtil.copyProperties(car, copy);
            copy.setId(null);
            copy.setCarId(null);
            copy.setCheckAdminId(car.getAdminId());
            copy.setOperateType(AuditTypeEnum.ADD.getCode());
            copy.setUseAdminId(opId);
            copy.setIsDeleted(IsDeletedEnum.NOT_DELETED.getCode());
            carCopyMapper.insert(copy);
            msg = "待审核";
        }
        operatorLogService.insert("添加车辆信息", "添加车辆", "1", opId, operator.getOpName(), orgId);
        /*if (true){
            throw new RuntimeException();
        }*/
        return GetResult.getResultSuccess("车辆信息添加成功！" + msg);
    }

    public String getOrgIdAllChild(String orgId) throws Exception {
        List<Organization> orgList = organizationService.getOrgIds(orgId);
        StringBuilder sb = new StringBuilder();
        for (Organization organization : orgList) {
            sb.append(organization.getOrgId()).append(",");
        }
        int size = sb.toString().length() - 1;
        return sb.toString().substring(0, size);
    }
}
